<?php
namespace plugin\ky_black\app\admin\controller;

use support\Request;
use support\Response;
use plugin\ky_black\app\admin\model\BlackCardSub;
use plugin\ky_black\app\admin\model\BlackCard;
use plugin\ky_black\app\admin\model\BlackCardSubBalanceLog;
use support\Db;

class BlackCardSubController extends BaseController
{
    /**
     * 子卡列表
     */
    public function list(Request $request): Response
    {
        $page = (int)$request->input('page', 1);
        $pageSize = (int)$request->input('limit', 15);
        $parentCardId = (int)$request->input('parent_card_id', 0);
        $keyword = $request->input('keyword', '');
        $status = $request->input('status', '');

        $query = BlackCardSub::with(['parentCard']);

        // 主卡ID筛选
        if ($parentCardId) {
            $query->where('parent_card_id', $parentCardId);
        }

        // 关键词搜索
        if ($keyword) {
            $query->where(function ($q) use ($keyword) {
                $q->where('sub_card_no', 'like', "%{$keyword}%")
                  ->orWhere('name', 'like', "%{$keyword}%")
                  ->orWhere('mobile', 'like', "%{$keyword}%");
            });
        }

        // 状态筛选
        if ($status !== '') {
            $query->where('status', (int)$status);
        }

        $total = $query->count();
        $list = $query->orderBy('sub_card_id', 'desc')
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get();

        return $this->success([
            'list' => $list,
            'total' => $total
        ]);
    }

    /**
     * 创建子卡
     */
    public function create(Request $request): Response
    {
        $data = $request->post();
        
        // 验证主卡是否存在
        $parentCard = BlackCard::find($data['parent_card_id']);
        if (!$parentCard) {
            return $this->error('主卡不存在');
        }

        // 生成子卡卡号
        $data['sub_card_no'] = BlackCardSub::generateSubCardNo();

        // 验证额度类型
        if ($data['limit_type'] === 'fixed') {
            if ($data['fixed_limit'] <= 0) {
                return $this->error('固定额度必须大于0');
            }
            // 固定额度模式下，共享额度为0
            $data['shared_limit'] = 0;
        } else {
            if ($data['shared_limit'] <= 0) {
                return $this->error('共享额度上限必须大于0');
            }
            // 共享额度模式下，固定额度为0
            $data['fixed_limit'] = 0;
        }

        try {
            $subCard = BlackCardSub::create($data);
            return $this->success($subCard, '创建成功');
        } catch (\Exception $e) {
            return $this->error('创建失败：' . $e->getMessage());
        }
    }

    /**
     * 更新子卡
     */
    public function update(Request $request): Response
    {
        $subCardId = $request->input('sub_card_id');
        $data = $request->post();

        if (!$subCardId) {
            return $this->error('参数错误');
        }

        try {
            $subCard = BlackCardSub::findOrFail($subCardId);

            // 验证额度类型
            if ($data['limit_type'] === 'fixed') {
                if ($data['fixed_limit'] <= 0) {
                    return $this->error('固定额度必须大于0');
                }
                $data['shared_limit'] = 0;
            } else {
                if ($data['shared_limit'] <= 0) {
                    return $this->error('共享额度上限必须大于0');
                }
                $data['fixed_limit'] = 0;
            }

            $subCard->update($data);
            return $this->success($subCard, '更新成功');
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除子卡
     */
    public function delete(Request $request): Response
    {
        $subCardId = $request->input('sub_card_id');
        if (!$subCardId) {
            return $this->error('参数错误');
        }

        try {
            $subCard = BlackCardSub::findOrFail($subCardId);
            $subCard->delete();
            return $this->success(null, '删除成功');
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 更新子卡状态
     */
    public function updateStatus(Request $request): Response
    {
        $subCardId = $request->input('sub_card_id');
        $status = (int)$request->input('status');

        if (!$subCardId) {
            return $this->error('参数错误');
        }

        try {
            $subCard = BlackCardSub::findOrFail($subCardId);
            $subCard->status = $status;
            $subCard->save();
            return $this->success(null, '状态更新成功');
        } catch (\Exception $e) {
            return $this->error('状态更新失败：' . $e->getMessage());
        }
    }

    /**
     * 获取子卡详情
     */
    public function detail(Request $request): Response
    {
        $subCardId = $request->input('id');
        if (!$subCardId) {
            return $this->error('参数错误');
        }

        $subCard = BlackCardSub::with(['parentCard'])->find($subCardId);
        if (!$subCard) {
            return $this->error('子卡不存在');
        }

        return $this->success($subCard);
    }

    /**
     * 分配余额
     */
    public function allocateBalance(Request $request): Response
    {
        $subCardId = $request->input('sub_card_id');
        $amount = (float)$request->input('amount');
        $remark = $request->input('remark', '');

        if (!$subCardId || $amount <= 0) {
            return $this->error('参数错误');
        }

        try {
            Db::transaction(function () use ($subCardId, $amount, $remark, $request) {
                // 获取子卡信息
                $subCard = BlackCardSub::findOrFail($subCardId);
                
                // 获取主卡信息
                $parentCard = BlackCard::where('card_id', $subCard->parent_card_id)->lockForUpdate()->first();
                if (!$parentCard) {
                    throw new \Exception('主卡不存在');
                }

                // 检查主卡余额
                if ($parentCard->balance < $amount) {
                    throw new \Exception('主卡余额不足');
                }

                // 更新主卡余额
                $beforeParentBalance = $parentCard->balance;
                $parentCard->balance -= $amount;
                $parentCard->save();

                // 更新子卡余额
                $beforeSubBalance = $subCard->balance ?? 0;
                $subCard->balance = ($subCard->balance ?? 0) + $amount;
                $subCard->save();

                // 记录余额分配日志
                BlackCardSubBalanceLog::create([
                    'parent_card_id' => $parentCard->card_id,
                    'parent_card_no' => $parentCard->card_no,
                    'sub_card_id' => $subCard->sub_card_id,
                    'sub_card_no' => $subCard->sub_card_no,
                    'amount' => $amount,
                    'before_balance' => $beforeSubBalance,
                    'after_balance' => $subCard->balance,
                    'remark' => $remark,
                    'operator_id' => $request->user->staff_id ?? 0,
                    'operator_name' => $request->user->real_name ?? '系统'
                ]);
            });

            return $this->success(null, '余额分配成功');
        } catch (\Exception $e) {
            return $this->error('余额分配失败：' . $e->getMessage());
        }
    }

    /**
     * 获取余额分配记录
     */
    public function balanceLog(Request $request): Response
    {
        $page = (int)$request->input('page', 1);
        $pageSize = (int)$request->input('limit', 15);
        $subCardId = (int)$request->input('sub_card_id', 0);
        $parentCardId = (int)$request->input('parent_card_id', 0);
        $startTime = $request->input('start_time', '');
        $endTime = $request->input('end_time', '');

        $query = BlackCardSubBalanceLog::with(['parentCard', 'subCard']);

        if ($subCardId) {
            $query->where('sub_card_id', $subCardId);
        }

        if ($parentCardId) {
            $query->where('parent_card_id', $parentCardId);
        }

        if ($startTime) {
            $query->where('created_at', '>=', $startTime);
        }

        if ($endTime) {
            $query->where('created_at', '<=', $endTime);
        }

        $total = $query->count();
        $list = $query->orderBy('log_id', 'desc')
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get();

        return $this->success([
            'list' => $list,
            'total' => $total
        ]);
    }
} 